<?php

if (!defined('ABSPATH')) { exit; }
?>
<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Most impactful products without needs', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php
        echo esc_html(sprintf(
            
            __('Top sellers that don\'t have any pa_need term assigned yet. Sourced from wp_aieo_temp_orders (completed + processing orders), variations rolled up to their parent product. Pick from this list first — every term you assign to one of these immediately powers Product Needs filtering, the AI shop assistant, and recommendations. %d products with sales are still missing needs.', 'ai-eshop-optimizer'),
            (int) $impactful_total_missing
        ));
        ?>
    </p>

    <?php if (empty($impactful)) : ?>
        <p style="background:#ecfdf5;padding:10px 14px;border-left:3px solid #15803d;border-radius:4px;font-size:13px;color:#14532d;">
            <?php esc_html_e('Every product with sales already has at least one need assigned. Nothing to action here.', 'ai-eshop-optimizer'); ?>
        </p>
    <?php else : ?>
        <table id="aieo-dmm-needs-impactful-table" class="widefat striped aieo-table aieo-attr-sortable-table">
            <thead>
                <tr>
                    <th data-sort-type="num"  style="width:80px;"><?php esc_html_e('Product ID', 'ai-eshop-optimizer'); ?> <span class="aieo-attr-dt-sort-ind">⇅</span></th>
                    <th data-sort-type="text"><?php esc_html_e('Title', 'ai-eshop-optimizer'); ?> <span class="aieo-attr-dt-sort-ind">⇅</span></th>
                    <th data-sort-type="text"><?php esc_html_e('SKU', 'ai-eshop-optimizer'); ?> <span class="aieo-attr-dt-sort-ind">⇅</span></th>
                    <th data-sort-type="num"  style="width:120px;text-align:right;"><?php esc_html_e('Qty sold', 'ai-eshop-optimizer'); ?> <span class="aieo-attr-dt-sort-ind">⇅</span></th>
                    <th data-sort-type="num" class="sorted-desc" style="width:150px;text-align:right;"><?php esc_html_e('Turnover', 'ai-eshop-optimizer'); ?> <span class="aieo-attr-dt-sort-ind">▼</span></th>
                    <th style="width:140px;"></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($impactful as $row) :
                $pid   = (int) $row['pid'];
                $title = (string) $row['title'];
                $sku   = (string) $row['sku'];
                $qty   = (int) $row['qty'];
                $turn  = (float) $row['turnover'];
                $edit_link = $row['edit_link'];
                $select_link = $row['select_link'];
                ?>
                <tr>
                    <td data-sort-value="<?php echo esc_attr((string) $pid); ?>"><?php echo (int) $pid; ?></td>
                    <td data-sort-value="<?php echo esc_attr($title); ?>">
                        <a href="<?php echo esc_url($edit_link); ?>" target="_blank">
                            <?php echo esc_html($title !== '' ? $title : '— deleted —'); ?>
                        </a>
                    </td>
                    <td data-sort-value="<?php echo esc_attr($sku); ?>"><code><?php echo esc_html($sku); ?></code></td>
                    <td data-sort-value="<?php echo esc_attr((string) $qty); ?>" style="text-align:right;"><?php echo esc_html(number_format_i18n($qty)); ?></td>
                    <td data-sort-value="<?php echo esc_attr((string) $turn); ?>" style="text-align:right;">
                        <?php
                        if (function_exists('wc_price')) {
                            echo wp_kses_post(wc_price($turn));
                        } else {
                            echo esc_html(number_format_i18n($turn, 2));
                        }
                        ?>
                    </td>
                    <td>
                        <a href="<?php echo esc_url($select_link); ?>" class="button button-primary button-small">
                            <?php esc_html_e('Edit needs', 'ai-eshop-optimizer'); ?>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <script>
        (function () {
            var table = document.getElementById('aieo-dmm-needs-impactful-table');
            if (!table) { return; }
            var thead = table.querySelector('thead');
            if (!thead) { return; }
            thead.addEventListener('click', function (evt) {
                var th = evt.target.closest('th[data-sort-type]');
                if (!th || !thead.contains(th)) { return; }
                var idx  = Array.prototype.indexOf.call(th.parentNode.children, th);
                var type = th.getAttribute('data-sort-type') || 'text';
                var cur  = th.classList.contains('sorted-asc')
                    ? 'asc'
                    : (th.classList.contains('sorted-desc') ? 'desc' : null);
                var next = cur === 'asc' ? 'desc' : 'asc';

                Array.prototype.forEach.call(thead.querySelectorAll('th'), function (otherTh) {
                    if (otherTh === th) { return; }
                    otherTh.classList.remove('sorted-asc', 'sorted-desc');
                    var ind = otherTh.querySelector('.aieo-attr-dt-sort-ind');
                    if (ind) { ind.textContent = '⇅'; }
                });
                th.classList.remove('sorted-asc', 'sorted-desc');
                th.classList.add(next === 'asc' ? 'sorted-asc' : 'sorted-desc');
                var ownInd = th.querySelector('.aieo-attr-dt-sort-ind');
                if (ownInd) { ownInd.textContent = next === 'asc' ? '▲' : '▼'; }

                var tbody = table.querySelector('tbody');
                var rows = Array.prototype.slice.call(tbody.children);
                rows.sort(function (a, b) {
                    var ac = a.children[idx];
                    var bc = b.children[idx];
                    if (!ac || !bc) { return 0; }
                    var av = ac.getAttribute('data-sort-value');
                    var bv = bc.getAttribute('data-sort-value');
                    if (av === null) { av = (ac.textContent || '').trim(); }
                    if (bv === null) { bv = (bc.textContent || '').trim(); }
                    if (type === 'num') {
                        var an = parseFloat(String(av).replace(/[^0-9.\-]/g, '')) || 0;
                        var bn = parseFloat(String(bv).replace(/[^0-9.\-]/g, '')) || 0;
                        return next === 'asc' ? an - bn : bn - an;
                    }
                    var cmp = String(av).localeCompare(String(bv), undefined, { sensitivity: 'base' });
                    return next === 'asc' ? cmp : -cmp;
                });
                rows.forEach(function (r) { tbody.appendChild(r); });
            });
        })();
        </script>
    <?php endif; ?>
</div>

<div class="aieo-dmm-section">
    <h2><?php esc_html_e('Product needs editor', 'ai-eshop-optimizer'); ?></h2>
    <p class="description">
        <?php esc_html_e('Pick a product, then check off which needs it addresses. Drag the selected chips to reorder.', 'ai-eshop-optimizer'); ?>
    </p>

    <div class="aieo-dmm-form" id="aieo-dmm-needs-editor" data-preselect-pid="<?php echo (int) $preselect_pid; ?>">
        <p>
            <label><?php esc_html_e('Product', 'ai-eshop-optimizer'); ?></label>
            <select id="aieo-dmm-needs-product" class="aieo-dmm-needs-product-search regular-text">
                <?php if ($preselect_pid > 0) : ?>
                    <?php $p = function_exists('wc_get_product') ? wc_get_product($preselect_pid) : null; ?>
                    <?php if ($p) : ?>
                        <option value="<?php echo (int) $preselect_pid; ?>" selected>
                            <?php echo esc_html($p->get_name() . ($p->get_sku() ? ' [' . $p->get_sku() . ']' : '')); ?>
                        </option>
                    <?php endif; ?>
                <?php endif; ?>
            </select>
        </p>

        <div id="aieo-dmm-needs-meta" style="display:none;">
            <h3 id="aieo-dmm-needs-title"></h3>
            <p><strong><?php esc_html_e('SKU:', 'ai-eshop-optimizer'); ?></strong> <span id="aieo-dmm-needs-sku"></span></p>
        </div>

        <div id="aieo-dmm-needs-selected" class="aieo-dmm-needs-zone">
            <h4><?php esc_html_e('Selected needs (drag to reorder)', 'ai-eshop-optimizer'); ?></h4>
            <ul class="aieo-dmm-chips"></ul>
        </div>

        <div id="aieo-dmm-needs-available" class="aieo-dmm-needs-zone">
            <div class="aieo-dmm-needs-toolbar" style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:8px;">
                <h4 style="margin:0;"><?php esc_html_e('Available needs', 'ai-eshop-optimizer'); ?></h4>
                <button type="button" class="button button-secondary" id="aieo-dmm-needs-create-toggle">
                    + <?php esc_html_e('New need', 'ai-eshop-optimizer'); ?>
                </button>
            </div>

            <div id="aieo-dmm-needs-create-form" style="display:none;background:#eef2ff;border:1px dashed #6366f1;border-radius:8px;padding:12px 14px;margin-bottom:10px;">
                <div style="display:grid;grid-template-columns:2fr 1fr auto;gap:8px;align-items:end;">
                    <div>
                        <label style="display:block;font-size:11px;color:#4338ca;font-weight:600;text-transform:uppercase;letter-spacing:.04em;margin-bottom:3px;">
                            <?php esc_html_e('Name', 'ai-eshop-optimizer'); ?>
                        </label>
                        <input type="text" id="aieo-dmm-needs-create-name" placeholder="<?php echo esc_attr__('e.g. Anti-frizz', 'ai-eshop-optimizer'); ?>" style="width:100%;">
                    </div>
                    <div>
                        <label style="display:block;font-size:11px;color:#4338ca;font-weight:600;text-transform:uppercase;letter-spacing:.04em;margin-bottom:3px;">
                            <?php esc_html_e('Slug', 'ai-eshop-optimizer'); ?>
                            <span style="font-weight:400;text-transform:none;color:#6b7280;">(<?php esc_html_e('optional', 'ai-eshop-optimizer'); ?>)</span>
                        </label>
                        <input type="text" id="aieo-dmm-needs-create-slug" placeholder="<?php echo esc_attr__('auto', 'ai-eshop-optimizer'); ?>" style="width:100%;">
                    </div>
                    <div>
                        <button type="button" class="button button-primary" id="aieo-dmm-needs-create-submit">
                            <?php esc_html_e('Create', 'ai-eshop-optimizer'); ?>
                        </button>
                    </div>
                </div>
                <label style="display:inline-flex;align-items:center;gap:6px;margin-top:10px;font-size:12px;color:#374151;">
                    <input type="checkbox" id="aieo-dmm-needs-create-hidden">
                    <?php esc_html_e('Internal only — hide from product-page rendering', 'ai-eshop-optimizer'); ?>
                </label>
                <div id="aieo-dmm-needs-create-msg" aria-live="polite" style="margin-top:6px;font-size:12px;"></div>
            </div>

            <div class="aieo-dmm-needs-search-wrap">
                <input
                    type="text"
                    id="aieo-dmm-needs-search"
                    class="aieo-dmm-needs-search"
                    placeholder="<?php echo esc_attr__('Search needs by name or slug…', 'ai-eshop-optimizer'); ?>"
                    autocomplete="off"
                >
                <div class="aieo-dmm-needs-search-meta" id="aieo-dmm-needs-search-meta" aria-live="polite"></div>
            </div>
            <ul class="aieo-dmm-checkboxes" id="aieo-dmm-needs-checkboxes">
                <?php foreach ($all_needs as $need) :
                    $is_hidden = !empty($need['hidden']);
                    $li_class  = $is_hidden ? 'is-hidden-need' : '';
                    ?>
                    <li class="<?php echo esc_attr($li_class); ?>"
                        data-need-name="<?php echo esc_attr(mb_strtolower((string) $need['name'])); ?>"
                        data-need-slug="<?php echo esc_attr((string) $need['slug']); ?>">
                        <label>
                            <input type="checkbox" name="need_ids[]" value="<?php echo (int) $need['term_id']; ?>">
                            <span><?php echo esc_html($need['name']); ?></span>
                            <?php if ($is_hidden) : ?>
                                <span style="display:inline-block;padding:1px 7px;background:#6b7280;color:#fff;border-radius:10px;font-size:10px;font-weight:700;letter-spacing:.02em;text-transform:uppercase;" title="<?php echo esc_attr__('This need is suppressed from product-page rendering. Used internally / for AI processing.', 'ai-eshop-optimizer'); ?>">
                                    <?php esc_html_e('Internal', 'ai-eshop-optimizer'); ?>
                                </span>
                            <?php endif; ?>
                        </label>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
        <script>
        (function () {
            var input  = document.getElementById('aieo-dmm-needs-search');
            var list   = document.getElementById('aieo-dmm-needs-checkboxes');
            var meta   = document.getElementById('aieo-dmm-needs-search-meta');
            if (!input || !list) { return; }
            var items = Array.prototype.slice.call(list.children);
            var total = items.length;

            function normalize(s) {
                // Lowercase + strip Greek + Latin diacritics so "Καθημερινη"
                // matches "Καθημερινή" and "anaplasi" matches "Aνάπλαση".
                return (s || '').toString().toLowerCase()
                    .normalize('NFD').replace(/[̀-ͯ]/g, '');
            }

            function filter() {
                var q = normalize(input.value.trim());
                var shown = 0;
                items.forEach(function (li) {
                    if (q === '') {
                        li.style.display = '';
                        shown++;
                        return;
                    }
                    var name = normalize(li.getAttribute('data-need-name'));
                    var slug = normalize(li.getAttribute('data-need-slug'));
                    var hit = name.indexOf(q) !== -1 || slug.indexOf(q) !== -1;
                    li.style.display = hit ? '' : 'none';
                    if (hit) { shown++; }
                });
                if (q === '') {
                    meta.textContent = '';
                } else if (shown === 0) {
                    meta.textContent = <?php echo wp_json_encode(__('No needs match.', 'ai-eshop-optimizer')); ?>;
                } else {
                    meta.textContent = shown + ' / ' + total;
                }
            }

            input.addEventListener('input', filter);
            // Esc clears the filter.
            input.addEventListener('keydown', function (e) {
                if (e.key === 'Escape' && input.value !== '') {
                    input.value = '';
                    filter();
                }
            });

            /* ---- Inline "Create new need" form ---- */
            var toggleBtn   = document.getElementById('aieo-dmm-needs-create-toggle');
            var createForm  = document.getElementById('aieo-dmm-needs-create-form');
            var createName  = document.getElementById('aieo-dmm-needs-create-name');
            var createSlug  = document.getElementById('aieo-dmm-needs-create-slug');
            var createHide  = document.getElementById('aieo-dmm-needs-create-hidden');
            var createBtn   = document.getElementById('aieo-dmm-needs-create-submit');
            var createMsg   = document.getElementById('aieo-dmm-needs-create-msg');

            if (toggleBtn && createForm) {
                toggleBtn.addEventListener('click', function () {
                    var open = createForm.style.display !== 'none';
                    createForm.style.display = open ? 'none' : 'block';
                    if (!open) { createName.focus(); }
                });
            }

            function setCreateMsg(text, kind) {
                if (!createMsg) { return; }
                createMsg.textContent = text || '';
                createMsg.style.color = kind === 'error' ? '#b91c1c'
                                      : (kind === 'success' ? '#15803d' : '#6b7280');
            }

            function appendNeedItem(payload) {
                // Build the same DOM shape as the PHP template so search +
                // hidden styling work without re-rendering.
                var li = document.createElement('li');
                if (payload.hidden) { li.className = 'is-hidden-need'; }
                li.setAttribute('data-need-name', (payload.name || '').toLowerCase());
                li.setAttribute('data-need-slug', payload.slug || '');

                var label = document.createElement('label');
                var cb = document.createElement('input');
                cb.type = 'checkbox';
                cb.name = 'need_ids[]';
                cb.value = String(payload.term_id);
                cb.checked = true;

                var nameSpan = document.createElement('span');
                nameSpan.textContent = payload.name;

                label.appendChild(cb);
                label.appendChild(nameSpan);

                if (payload.hidden) {
                    var badge = document.createElement('span');
                    badge.style.cssText = 'display:inline-block;padding:1px 7px;background:#6b7280;color:#fff;border-radius:10px;font-size:10px;font-weight:700;letter-spacing:.02em;text-transform:uppercase;';
                    badge.textContent = <?php echo wp_json_encode(__('Internal', 'ai-eshop-optimizer')); ?>;
                    label.appendChild(badge);
                }

                li.appendChild(label);
                list.insertBefore(li, list.firstChild);
                items = Array.prototype.slice.call(list.children);
                total = items.length;
            }

            if (createBtn) {
                createBtn.addEventListener('click', function () {
                    var name = (createName.value || '').trim();
                    if (name === '') {
                        setCreateMsg(<?php echo wp_json_encode(__('Name is required.', 'ai-eshop-optimizer')); ?>, 'error');
                        createName.focus();
                        return;
                    }
                    createBtn.disabled = true;
                    setCreateMsg(<?php echo wp_json_encode(__('Creating…', 'ai-eshop-optimizer')); ?>, 'info');

                    var fd = new FormData();
                    fd.append('action', 'aieo_dmm_needs_create_term');
                    fd.append('nonce', <?php echo wp_json_encode(wp_create_nonce(AIEO_DMM::NONCE_ACTION)); ?>);
                    fd.append('name', name);
                    fd.append('slug', (createSlug.value || '').trim());
                    if (createHide && createHide.checked) { fd.append('hidden', '1'); }

                    fetch(<?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>, {
                        method: 'POST',
                        credentials: 'same-origin',
                        body: fd
                    }).then(function (r) { return r.json(); })
                      .then(function (resp) {
                          createBtn.disabled = false;
                          if (resp && resp.success && resp.data && resp.data.term_id) {
                              appendNeedItem(resp.data);
                              setCreateMsg(<?php echo wp_json_encode(__('Created. Tick remaining boxes and Save.', 'ai-eshop-optimizer')); ?>, 'success');
                              createName.value = '';
                              createSlug.value = '';
                              if (createHide) { createHide.checked = false; }
                              filter();
                          } else {
                              var msg = (resp && resp.data && resp.data.message) ? resp.data.message
                                  : <?php echo wp_json_encode(__('Could not create the need.', 'ai-eshop-optimizer')); ?>;
                              setCreateMsg(msg, 'error');
                          }
                      })
                      .catch(function () {
                          createBtn.disabled = false;
                          setCreateMsg(<?php echo wp_json_encode(__('Network error — try again.', 'ai-eshop-optimizer')); ?>, 'error');
                      });
                });
            }
        })();
        </script>

        <p class="submit">
            <button type="button" class="button button-primary" id="aieo-dmm-needs-save">
                <?php esc_html_e('Save needs for this product', 'ai-eshop-optimizer'); ?>
            </button>
        </p>
    </div>
</div>
