<?php

if (!defined('ABSPATH')) { exit; }
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Free gifts', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('When a customer\'s qualifying subtotal crosses the threshold, a free gift product is added to their cart automatically. Qualifying products can be restricted by brand, by category, or both (with AND/OR). Leave a dimension empty to mean "any".', 'ai-eshop-optimizer'); ?>
    </p>

    <form id="aieo-dmm-brand-gift-form" class="aieo-dmm-form">
        <input type="hidden" name="id" value="0">

        <?php
        
        include __DIR__ . '/_partials/targeting-selector.php';
        ?>

        <!-- Gift-specific side-cart visibility toggles. NOT in the shared
             partial because the Exchanger feed builder doesn't render
             anything in the side cart. -->
        <div class="aieo-dmm-grid">
            <p>
                <label class="aieo-dmm-choice" style="margin-top:6px;">
                    <input type="checkbox" name="show_banner" value="1" checked>
                    <?php esc_html_e('Show top banner in side cart', 'ai-eshop-optimizer'); ?>
                </label>
                <label class="aieo-dmm-choice" style="display:block;margin-top:4px;">
                    <input type="checkbox" name="show_rewards" value="1" checked>
                    <?php esc_html_e('Show reward cards under cart items', 'ai-eshop-optimizer'); ?>
                </label>
                <span class="description" style="display:block;margin-top:4px;">
                    <?php esc_html_e('Either / both / neither — the gift still gets added to the cart when the threshold is met regardless of these toggles.', 'ai-eshop-optimizer'); ?>
                </span>
            </p>
        </div>

        <!-- ============================================================
             Type-specific actionable section — what differs per offer
             type. For gifts: gift product picker + on-cart messaging
             + banner imagery. For discounts: percent + application
             scope. For free shipping: action when matched.
             ============================================================ -->
        <h3 style="margin:24px 0 6px;"><?php esc_html_e('Gift products', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php esc_html_e('The actual reward — what the customer receives when they qualify. Customer gets the first in-stock option, or picks one if the presentation mode is "list" / "dropdown".', 'ai-eshop-optimizer'); ?>
        </p>
        <p>
            <select name="gift_product_ids[]" multiple class="aieo-dmm-product-select regular-text" style="width:100%;"></select>
        </p>

        <p style="margin-top:10px">
            <label for="aieo_dmm_gift_before_text"><?php esc_html_e('Message before threshold (HTML)', 'ai-eshop-optimizer'); ?></label>
        </p>
        <?php
        wp_editor('', 'aieo_dmm_gift_before_text', array(
            'textarea_name' => 'before_text',
            'textarea_rows' => 3,
            'teeny'         => true,
            'media_buttons' => false,
            'quicktags'     => true,
        ));
        ?>
        <p style="margin-top:8px;">
            <label><?php esc_html_e('Banner image — before threshold', 'ai-eshop-optimizer'); ?></label>
            <span class="aieo-dmm-gift-image-widget" data-target="before_image_id">
                <input type="hidden" name="before_image_id" value="0">
                <img class="aieo-dmm-gift-image-preview" src="" alt="" style="display:none;max-width:140px;max-height:80px;border:1px solid #ddd;border-radius:4px;vertical-align:middle;margin-right:8px;">
                <button type="button" class="button aieo-dmm-gift-image-pick"><?php esc_html_e('Choose image', 'ai-eshop-optimizer'); ?></button>
                <button type="button" class="button aieo-dmm-gift-image-clear" style="display:none;"><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>
            </span>
            <span class="description" style="display:block;margin-top:4px;"><?php esc_html_e('Optional banner shown in the side cart while the shopper has not yet hit the threshold.', 'ai-eshop-optimizer'); ?></span>
        </p>

        <p style="margin-top:16px">
            <label for="aieo_dmm_gift_after_text"><?php esc_html_e('Message after threshold (HTML)', 'ai-eshop-optimizer'); ?></label>
        </p>
        <?php
        wp_editor('', 'aieo_dmm_gift_after_text', array(
            'textarea_name' => 'after_text',
            'textarea_rows' => 3,
            'teeny'         => true,
            'media_buttons' => false,
            'quicktags'     => true,
        ));
        ?>
        <p style="margin-top:8px;">
            <label><?php esc_html_e('Banner image — after threshold', 'ai-eshop-optimizer'); ?></label>
            <span class="aieo-dmm-gift-image-widget" data-target="after_image_id">
                <input type="hidden" name="after_image_id" value="0">
                <img class="aieo-dmm-gift-image-preview" src="" alt="" style="display:none;max-width:140px;max-height:80px;border:1px solid #ddd;border-radius:4px;vertical-align:middle;margin-right:8px;">
                <button type="button" class="button aieo-dmm-gift-image-pick"><?php esc_html_e('Choose image', 'ai-eshop-optimizer'); ?></button>
                <button type="button" class="button aieo-dmm-gift-image-clear" style="display:none;"><?php esc_html_e('Remove', 'ai-eshop-optimizer'); ?></button>
            </span>
            <span class="description" style="display:block;margin-top:4px;"><?php esc_html_e('Optional banner shown when the shopper has qualified.', 'ai-eshop-optimizer'); ?></span>
        </p>

        <h3 style="margin:24px 0 6px;"><?php esc_html_e('Banner colors (optional)', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php esc_html_e('Override the default banner colors per offer. Leave empty to use the side-cart default styling.', 'ai-eshop-optimizer'); ?>
        </p>
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Banner background — before threshold', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="bar_bg_before" value="" class="aieo-dmm-bg-color">
            </p>
            <p>
                <label><?php esc_html_e('Bar progress color — before', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="bar_fg_before" value="" class="aieo-dmm-bg-color">
            </p>
            <p>
                <label><?php esc_html_e('Banner background — after threshold', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="bar_bg_after" value="" class="aieo-dmm-bg-color">
            </p>
            <p>
                <label><?php esc_html_e('Bar progress color — after', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="bar_fg_after" value="" class="aieo-dmm-bg-color">
            </p>
            <p>
                <label><?php esc_html_e('Gift line background (in cart)', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="gift_item_bg" value="" class="aieo-dmm-bg-color">
            </p>
        </div>

        <h3 style="margin:24px 0 6px;"><?php esc_html_e('Campaign type', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php esc_html_e('Marketing label, used for reporting only — does not change behaviour. Use "Sample" when the gifts are zero-value items not sold elsewhere; "Product" when they are full-value items also sold normally; "Mixed" when the campaign includes both.', 'ai-eshop-optimizer'); ?>
        </p>
        <p>
            <select name="gift_kind">
                <option value="product"><?php esc_html_e('Product (full-value items also sold normally)', 'ai-eshop-optimizer'); ?></option>
                <option value="sample"><?php esc_html_e('Sample (zero-value items, gift only)', 'ai-eshop-optimizer'); ?></option>
                <option value="mixed"><?php esc_html_e('Mixed (both types)', 'ai-eshop-optimizer'); ?></option>
            </select>
        </p>

        <h3 style="margin:24px 0 6px;"><?php esc_html_e('Display', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php esc_html_e('Choose how the gift offer is shown in the side cart and when. The gift still gets added to the cart when the threshold is met regardless of these toggles.', 'ai-eshop-optimizer'); ?>
        </p>
        <div class="aieo-dmm-grid">
            <p>
                <label><?php esc_html_e('Presentation', 'ai-eshop-optimizer'); ?></label>
                <select name="presentation_mode">
                    <option value="auto"><?php esc_html_e('Auto — single gift = label, multiple = list of cards', 'ai-eshop-optimizer'); ?></option>
                    <option value="list"><?php esc_html_e('List of cards (one per gift)', 'ai-eshop-optimizer'); ?></option>
                    <option value="dropdown"><?php esc_html_e('Single card with dropdown selector', 'ai-eshop-optimizer'); ?></option>
                </select>
            </p>
            <p>
                <label class="aieo-dmm-choice" style="margin-top:24px;">
                    <input type="checkbox" name="show_when_pending" value="1" checked>
                    <?php esc_html_e('Show preview before threshold is met', 'ai-eshop-optimizer'); ?>
                </label>
                <span class="description" style="display:block;margin-top:4px;">
                    <?php esc_html_e('Off = the gift offer block stays hidden until the cart qualifies (no "spend X more" prompt).', 'ai-eshop-optimizer'); ?>
                </span>
            </p>
        </div>

        <h3 style="margin:24px 0 6px;"><?php esc_html_e('Wording (optional overrides)', 'ai-eshop-optimizer'); ?></h3>
        <p class="description" style="margin:0 0 8px;">
            <?php
            printf(
                
                esc_html__('Override the default copy. Tokens: %1$s expands to the remaining amount (e.g. €5.00); %2$s expands to the brand / category / need name. Leave empty to use the default translatable string.', 'ai-eshop-optimizer'),
                '<code>{remaining}</code>',
                '<code>{brand}</code>'
            );
            ?>
        </p>
        <div class="aieo-dmm-grid">
            <p style="grid-column:1 / -1;">
                <label><?php esc_html_e('Headline — pending (threshold not yet met)', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="headline_pending" value="" class="large-text"
                       placeholder="🎁 Free gift waiting — spend {remaining} more on {brand}">
            </p>
            <p style="grid-column:1 / -1;">
                <label><?php esc_html_e('Headline — qualified (threshold met)', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="headline_qualified" value="" class="large-text"
                       placeholder="🎁 Pick your free gift from {brand}">
            </p>
            <p>
                <label><?php esc_html_e('Per-card pill — locked', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="pill_locked" value="" class="regular-text"
                       placeholder="Spend {remaining} more">
            </p>
            <p>
                <label><?php esc_html_e('Per-card pill — available', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="pill_available" value="" class="regular-text"
                       placeholder="Tap to swap">
            </p>
            <p>
                <label><?php esc_html_e('Per-card pill — claimed', 'ai-eshop-optimizer'); ?></label>
                <input type="text" name="pill_claimed" value="" class="regular-text"
                       placeholder="Claimed">
            </p>
        </div>

        <p class="submit">
            <button type="submit" class="button button-primary aieo-dmm-gift-save-btn" data-action="aieo_dmm_brand_gift_save">
                <?php esc_html_e('Save offer', 'ai-eshop-optimizer'); ?>
            </button>
            <button type="button" class="button aieo-dmm-gift-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><?php esc_html_e('Current offers', 'ai-eshop-optimizer'); ?></h3>
    <div id="aieo-dmm-brand-gifts-empty" style="<?php echo empty($offers) ? '' : 'display:none;'; ?>">
        <p><?php esc_html_e('No offers defined yet.', 'ai-eshop-optimizer'); ?></p>
    </div>
    <table id="aieo-dmm-brand-gifts-table" class="widefat striped aieo-table" style="<?php echo empty($offers) ? 'display:none;' : ''; ?>">
        <thead>
            <tr>
                <th><?php esc_html_e('Label', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Brands', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Categories', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Op', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Threshold', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Gifts', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Window', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Enabled', 'ai-eshop-optimizer'); ?></th>
                <th></th>
            </tr>
        </thead>
        <tbody id="aieo-dmm-brand-gifts-rows">
            <?php
            if (!empty($offers) && is_object($module)) {
                foreach ($offers as $o) {
                    
                    echo $module->render_offer_row($o);
                }
            }
            ?>
        </tbody>
    </table>
</div>

<script>
jQuery(function ($) {
    var $form  = $('#aieo-dmm-brand-gift-form');
    var $tbody = $('#aieo-dmm-brand-gifts-rows');
    var $table = $('#aieo-dmm-brand-gifts-table');
    var $empty = $('#aieo-dmm-brand-gifts-empty');
    var $saveBtn   = $form.find('.aieo-dmm-gift-save-btn');
    var $cancelBtn = $form.find('.aieo-dmm-gift-cancel-btn');
    var saveLabelDefault = $saveBtn.text();
    var saveLabelEdit    = '<?php echo esc_js(__('Update offer', 'ai-eshop-optimizer')); ?>';

    /**
     * Replace the underlying <select> options for a Select2 multi-
     * select with the (id, name) pairs from a saved offer, then
     * trigger 'change' so Select2 re-renders the chips.
     */
    function setSelect2Pairs($select, ids, names) {
        if (!$select.length) { return; }
        $select.empty();
        if (!ids || !ids.length) { $select.trigger('change'); return; }
        for (var i = 0; i < ids.length; i++) {
            var id = parseInt(ids[i], 10);
            if (!id) continue;
            var name = (names && names[i]) ? String(names[i]) : ('#' + id);
            $select.append(new Option(name, String(id), true, true));
        }
        $select.trigger('change');
    }

    function setEditor(editorId, html) {
        if (window.tinymce) {
            var ed = tinymce.get(editorId);
            if (ed) { ed.setContent(html || ''); return; }
        }
        // tinymce not ready — fall back to the textarea
        $('#' + editorId).val(html || '');
    }

    function setImage($widget, attachmentId, url) {
        $widget.find('input[type=hidden]').val(attachmentId || 0);
        var $preview = $widget.find('.aieo-dmm-gift-image-preview');
        var $clear   = $widget.find('.aieo-dmm-gift-image-clear');
        if (attachmentId && url) {
            $preview.attr('src', url).show();
            $clear.show();
        } else {
            $preview.attr('src', '').hide();
            $clear.hide();
        }
    }

    function resetForm() {
        $form[0].reset();
        $form.find('[name=id]').val(0);
        setSelect2Pairs($form.find('.aieo-dmm-brand-select'),    [], []);
        setSelect2Pairs($form.find('.aieo-dmm-category-select'), [], []);
        setSelect2Pairs($form.find('.aieo-dmm-need-select'),     [], []);
        setSelect2Pairs($form.find('.aieo-dmm-product-select'),  [], []);
        setEditor('aieo_dmm_gift_before_text', '');
        setEditor('aieo_dmm_gift_after_text',  '');
        $form.find('.aieo-dmm-gift-image-widget').each(function () { setImage($(this), 0, ''); });
        $saveBtn.text(saveLabelDefault);
        $cancelBtn.hide();
    }

    // WP Media picker for the two banner image widgets.
    var mediaFrames = {};
    $form.on('click', '.aieo-dmm-gift-image-pick', function (e) {
        e.preventDefault();
        var $widget = $(this).closest('.aieo-dmm-gift-image-widget');
        var key = $widget.data('target');
        if (!mediaFrames[key]) {
            mediaFrames[key] = wp.media({
                title:    '<?php echo esc_js(__('Select banner image', 'ai-eshop-optimizer')); ?>',
                button:   { text: '<?php echo esc_js(__('Use this image', 'ai-eshop-optimizer')); ?>' },
                library:  { type: 'image' },
                multiple: false,
            });
            mediaFrames[key].on('select', function () {
                var att = mediaFrames[key].state().get('selection').first().toJSON();
                var url = att.sizes && att.sizes.medium ? att.sizes.medium.url : att.url;
                setImage($widget, att.id, url);
            });
        }
        mediaFrames[key].open();
    });
    $form.on('click', '.aieo-dmm-gift-image-clear', function (e) {
        e.preventDefault();
        setImage($(this).closest('.aieo-dmm-gift-image-widget'), 0, '');
    });

    // EDIT — populate the form with the row's saved data.
    $tbody.on('click', '.aieo-dmm-edit-gift', function () {
        var data = $(this).closest('tr').data('offer');
        if (!data || !data.id) { return; }
        $form[0].reset();
        $form.find('[name=id]').val(data.id);
        $form.find('[name=label]').val(data.label || '');
        $form.find('[name=min_subtotal]').val(data.min_subtotal || 0);
        $form.find('[name=date_from]').val(data.date_from || '');
        $form.find('[name=date_to]').val(data.date_to || '');
        $form.find('[name=enabled]').prop('checked', !!data.enabled);
        $form.find('[name=show_banner]').prop('checked',  data.show_banner  === undefined ? true : !!data.show_banner);
        $form.find('[name=show_rewards]').prop('checked', data.show_rewards === undefined ? true : !!data.show_rewards);
        // Type / display / wording controls.
        $form.find('[name=gift_kind]').val(['product','sample','mixed'].indexOf(data.gift_kind) >= 0 ? data.gift_kind : 'product');
        $form.find('[name=presentation_mode]').val(['auto','list','dropdown'].indexOf(data.presentation_mode) >= 0 ? data.presentation_mode : 'auto');
        $form.find('[name=show_when_pending]').prop('checked', data.show_when_pending === undefined ? true : !!data.show_when_pending);
        ['headline_pending','headline_qualified','pill_locked','pill_available','pill_claimed'].forEach(function (key) {
            $form.find('input[name="' + key + '"]').val(data[key] || '');
        });
        var op = (data.rule_operator === 'OR') ? 'OR' : 'AND';
        $form.find('[name=rule_operator][value="' + op + '"]').prop('checked', true);
        // Positive targeting + product picker — disambiguate by `name`
        // so we don't accidentally also write into the exclusion pickers
        // (which share the same .aieo-dmm-brand-select / category /
        // need CSS classes for Select2 init).
        setSelect2Pairs($form.find('select[name="brand_term_ids[]"]'),    data.brand_term_ids,    data.brand_term_names);
        setSelect2Pairs($form.find('select[name="category_term_ids[]"]'), data.category_term_ids, data.category_term_names);
        setSelect2Pairs($form.find('select[name="need_term_ids[]"]'),     data.need_term_ids,     data.need_term_names);
        setSelect2Pairs($form.find('select[name="gift_product_ids[]"]'),  data.gift_product_ids,  data.gift_product_names);
        // Negative targeting (exclusions) — same shape, separate name.
        setSelect2Pairs($form.find('select[name="excluded_brand_ids[]"]'),    data.excluded_brand_ids    || [], data.excluded_brand_names    || []);
        setSelect2Pairs($form.find('select[name="excluded_category_ids[]"]'), data.excluded_category_ids || [], data.excluded_category_names || []);
        setSelect2Pairs($form.find('select[name="excluded_need_ids[]"]'),     data.excluded_need_ids     || [], data.excluded_need_names     || []);
        // Targeting product pickers — hydrate from server-resolved
        // {id,text,type,status,parent_id} pairs so chips show with context.
        if (window.aieoProdPicker) {
            window.aieoProdPicker.hydrate($form[0], 'product_ids',          data.product_products  || []);
            window.aieoProdPicker.hydrate($form[0], 'excluded_product_ids', data.excluded_products || []);
        }
        setEditor('aieo_dmm_gift_before_text', data.before_text || '');
        setEditor('aieo_dmm_gift_after_text',  data.after_text  || '');
        // Color fields — wp-color-picker stores its UI on the input,
        // setting `.val()` alone won't update the swatch. Use the
        // public iris API to refresh the swatch on edit.
        ['bar_bg_before','bar_bg_after','bar_fg_before','bar_fg_after','gift_item_bg'].forEach(function (key) {
            var $input = $form.find('input[name="' + key + '"]');
            if (!$input.length) return;
            var v = data[key] || '';
            $input.val(v);
            if ($input.hasClass('wp-color-picker')) {
                try { $input.iris('color', v || ''); } catch (e) { /* ignore */ }
            }
        });
        // Pre-fill the two banner-image widgets from the saved row.
        // The label resolver on the server emits *_image_url + *_image_id
        // (see fetch_offer_with_labels()) so we don't have to query the
        // attachment URL client-side.
        setImage($form.find('[data-target=before_image_id]'),
                 parseInt(data.before_image_id, 10) || 0,
                 (data.before_image_url || ''));
        setImage($form.find('[data-target=after_image_id]'),
                 parseInt(data.after_image_id, 10) || 0,
                 (data.after_image_url || ''));
        $saveBtn.html(saveLabelEdit);
        $cancelBtn.show();
        $('html, body').animate({ scrollTop: $form.offset().top - 60 }, 200);
    });

    // CANCEL EDIT
    $cancelBtn.on('click', resetForm);

    // After save — splice the returned row into the table without reload.
    $form.on('aieo-dmm:saved', function (e, data) {
        if (!data || !data.row_html) { return; }
        var $newRow  = $(data.row_html);
        var $existing = $tbody.find('tr[data-id="' + data.row.id + '"]');
        if ($existing.length) {
            $existing.replaceWith($newRow);
        } else {
            $tbody.prepend($newRow);
            $empty.hide();
            $table.show();
        }
        // Briefly highlight the row so the admin sees what changed.
        $newRow.css('background', '#fff3cd');
        setTimeout(function () {
            $newRow.css({ transition: 'background 1s', background: '' });
        }, 20);
        resetForm();
    });
});
</script>
