/* GT BOGO Engine PRO — Rules Manager JS
 * Extended: tags targeting, exclude_sale, PRO element IDs (gtbrm-*)
 * Compatible with page-rules-manager.php
 */
(function(){
'use strict';

var R = typeof gtbrData !== 'undefined' ? gtbrData : {};
var nonce     = R.nonce     || '';
var srchNonce = R.srchNonce || '';
var ajaxUrl   = R.ajaxUrl   || (typeof gtBogoAdmin !== 'undefined' ? gtBogoAdmin.ajaxUrl : '');

var selectedCats  = {};
var selectedProds = {};
var catTimer = null;
var prodTimer = null;
var tagTimer  = null;
var selectedTags = {};

/* ── Show / hide editor ──────────────────────────────────────────────── */
window.gtbrShowEditor = function(id) {
    selectedCats = {}; selectedProds = {};
    renderChips('cats'); renderChips('prods');
    document.getElementById('gtbr-categories').value = '';
    document.getElementById('gtbr-products').value   = '';
    document.getElementById('gtbr-cat-results').style.display  = 'none';
    document.getElementById('gtbr-prod-results').style.display = 'none';
    document.getElementById('gtbr-cat-search').value  = '';
    document.getElementById('gtbr-prod-search').value = '';

    if (id > 0) {
        document.getElementById('gtbr-editor-title').textContent = 'Edit Rule';
        document.getElementById('gtbr-status').textContent = 'Loading...';
        var fd = new FormData();
        fd.append('action','gtbogo_get_rule'); fd.append('nonce',nonce); fd.append('rule_id',id);
        fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
        .then(function(r){return r.json();})
        .then(function(res){
            if(!res.success){document.getElementById('gtbr-status').textContent='Error loading rule.';return;}
            var d = res.data;
            document.getElementById('gtbr-id').value        = d.id;
            document.getElementById('gtbr-name').value      = d.name||'';
            document.getElementById('gtbr-priority').value  = d.priority||10;
            document.getElementById('gtbr-buy').value       = d.buy_quantity||1;
            document.getElementById('gtbr-get').value       = d.get_quantity||1;
            document.getElementById('gtbr-disc-type').value = d.discount_type||'percentage';
            document.getElementById('gtbr-disc-val').value  = d.discount_value||100;
            document.getElementById('gtbr-apply-to').value  = d.apply_to||'cheapest';
            document.getElementById('gtbr-min-cart').value  = d.min_cart_total||0;
            document.getElementById('gtbr-max-uses').value  = d.max_uses||1;
            document.getElementById('gtbr-start').value     = d.start_date||'';
            document.getElementById('gtbr-end').value       = d.end_date||'';
            // Pre-load categories
            if(d.categories){
                var cids = d.categories.split(',').filter(Boolean);
                if(cids.length){
                    var fd2=new FormData(); fd2.append('action','gtbogo_search_categories');
                    fd2.append('nonce',srchNonce); fd2.append('ids',cids.join(','));
                    fetch(ajaxUrl,{method:'POST',body:fd2,credentials:'same-origin'})
                    .then(function(r){return r.json();}).then(function(res){
                        if(res.success&&res.data&&res.data.categories){
                            res.data.categories.forEach(function(c){selectedCats[c.id]=c.name;});
                            renderChips('cats');
                        }
                    });
                }
            }
            // Pre-load products
            if(d.products){
                var pids = d.products.split(',').filter(Boolean);
                if(pids.length){
                    var fd3=new FormData(); fd3.append('action','gtbogo_search_products');
                    fd3.append('nonce',srchNonce); fd3.append('ids',pids.join(','));
                    fetch(ajaxUrl,{method:'POST',body:fd3,credentials:'same-origin'})
                    .then(function(r){return r.json();}).then(function(res){
                        if(res.success&&res.data&&res.data.products){
                            res.data.products.forEach(function(p){selectedProds[p.id]=p.name;});
                            renderChips('prods');
                        }
                    });
                }
            }
            document.getElementById('gtbr-status').textContent = '';
        });
    } else {
        document.getElementById('gtbr-editor-title').textContent = 'New Rule';
        document.getElementById('gtbr-id').value        = '0';
        document.getElementById('gtbr-name').value      = '';
        document.getElementById('gtbr-priority').value  = '10';
        document.getElementById('gtbr-buy').value       = '1';
        document.getElementById('gtbr-get').value       = '1';
        document.getElementById('gtbr-disc-type').value = 'percentage';
        document.getElementById('gtbr-disc-val').value  = '100';
        document.getElementById('gtbr-apply-to').value  = 'cheapest';
        document.getElementById('gtbr-min-cart').value  = '0';
        document.getElementById('gtbr-max-uses').value  = '1';
        document.getElementById('gtbr-start').value     = '';
        document.getElementById('gtbr-end').value       = '';
        document.getElementById('gtbr-status').textContent = '';
    }
    document.getElementById('gtbr-editor').style.display = '';
    document.getElementById('gtbr-editor').scrollIntoView({behavior:'smooth',block:'start'});
    // Auto-discover store inventory on open — show real products/categories immediately
    gtbrSearchCats('');
    gtbrSearchProds('');
};

window.gtbrHideEditor = function() {
    document.getElementById('gtbr-editor').style.display = 'none';
};

/* ── Save rule ───────────────────────────────────────────────────────── */
window.gtbrSave = function() {
    var btn = document.getElementById('gtbr-save-btn');
    var status = document.getElementById('gtbr-status');
    btn.disabled = true; btn.textContent = 'Saving\u2026';
    status.textContent = '';

    var fd = new FormData();
    fd.append('action','gtbogo_save_rule');
    fd.append('nonce',nonce);
    fd.append('rule_id',    document.getElementById('gtbr-id').value);
    fd.append('name',       document.getElementById('gtbr-name').value);
    fd.append('priority',   document.getElementById('gtbr-priority').value);
    fd.append('buy_quantity',document.getElementById('gtbr-buy').value);
    fd.append('get_quantity',document.getElementById('gtbr-get').value);
    fd.append('discount_type',document.getElementById('gtbr-disc-type').value);
    fd.append('discount_value',document.getElementById('gtbr-disc-val').value);
    fd.append('apply_to',   document.getElementById('gtbr-apply-to').value);
    fd.append('min_cart_total',document.getElementById('gtbr-min-cart').value);
    fd.append('max_uses',   document.getElementById('gtbr-max-uses').value);
    fd.append('start_date', document.getElementById('gtbr-start').value);
    fd.append('end_date',   document.getElementById('gtbr-end').value);
    fd.append('categories', document.getElementById('gtbr-categories').value);
    fd.append('products',   document.getElementById('gtbr-products').value);

    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();})
    .then(function(res){
        if(res.success){
            status.style.color='#22c55e'; status.textContent='Saved.';
            setTimeout(function(){ location.reload(); }, 800);
        } else {
            status.style.color='#ef4444'; status.textContent='Error: '+(res.data&&res.data.message?res.data.message:'Unknown error');
            btn.disabled=false; btn.textContent='Save Rule';
        }
    }).catch(function(){
        status.style.color='#ef4444'; status.textContent='Connection error.';
        btn.disabled=false; btn.textContent='Save Rule';
    });
};

/* ── Toggle rule ─────────────────────────────────────────────────────── */
window.gtbrToggle = function(id, btn) {
    var fd=new FormData(); fd.append('action','gtbogo_toggle_rule');
    fd.append('nonce',nonce); fd.append('rule_id',id);
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();}).then(function(res){
        if(res.success){ location.reload(); }
    });
};

/* ── Delete rule ─────────────────────────────────────────────────────── */
window.gtbrDelete = function(id) {
    if(!confirm('Delete this rule? This cannot be undone.')) return;
    var fd=new FormData(); fd.append('action','gtbogo_delete_rule');
    fd.append('nonce',nonce); fd.append('rule_id',id);
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();}).then(function(res){
        if(res.success){
            var row=document.getElementById('gtbr-row-'+id);
            if(row) row.remove();
        }
    });
};

/* ── Chip render ─────────────────────────────────────────────────────── */
function renderChips(type) {
    var sel   = type==='cats' ? selectedCats : selectedProds;
    var wrap  = document.getElementById(type==='cats' ? 'gtbr-cats-chips' : 'gtbr-prods-chips');
    var input = document.getElementById(type==='cats' ? 'gtbr-categories' : 'gtbr-products');
    if(!wrap) return;
    wrap.innerHTML = '';
    Object.keys(sel).forEach(function(id){
        var chip = document.createElement('span');
        chip.style.cssText = 'display:inline-flex;align-items:center;gap:6px;background:rgba(225,0,0,0.12);border:1px solid rgba(225,0,0,0.3);border-radius:20px;padding:4px 10px 4px 12px;font-size:12px;color:#fff';
        chip.innerHTML = escHtml(sel[id]) + ' <button onclick="gtbrRemoveChip(\'' + type + '\',' + id + ')" style="background:none;border:none;color:#f87171;cursor:pointer;font-size:14px;line-height:1;padding:0">&times;</button>';
        wrap.appendChild(chip);
    });
    input.value = Object.keys(sel).join(',');
}

window.gtbrRemoveChip = function(type, id) {
    if(type==='cats') { delete selectedCats[id]; renderChips('cats'); }
    else              { delete selectedProds[id]; renderChips('prods'); }
};

function escHtml(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

/* ── Category search ─────────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', function(){
    var catSearch  = document.getElementById('gtbr-cat-search');
    var prodSearch = document.getElementById('gtbr-prod-search');
    if(catSearch) catSearch.addEventListener('input', function(){
        clearTimeout(catTimer);
        var q = this.value.trim();
        if(!q){ document.getElementById('gtbr-cat-results').style.display='none'; return; }
        catTimer = setTimeout(function(){ gtbrSearchCats(q); }, 300);
    });
    if(prodSearch) prodSearch.addEventListener('input', function(){
        clearTimeout(prodTimer);
        var q = this.value.trim();
        if(!q){ document.getElementById('gtbr-prod-results').style.display='none'; return; }
        prodTimer = setTimeout(function(){ gtbrSearchProds(q); }, 300);
    });
    // Hide results on outside click
    document.addEventListener('click', function(e){
        if(!e.target.closest('#gtbr-cat-results') && e.target.id !== 'gtbr-cat-search')
            document.getElementById('gtbr-cat-results') && (document.getElementById('gtbr-cat-results').style.display='none');
        if(!e.target.closest('#gtbr-prod-results') && e.target.id !== 'gtbr-prod-search')
            document.getElementById('gtbr-prod-results') && (document.getElementById('gtbr-prod-results').style.display='none');
    });
});

function gtbrSearchCats(q) {
    var box = document.getElementById('gtbr-cat-results');
    box.innerHTML='<div style="padding:12px;color:#64748b;font-size:13px">Searching...</div>';
    box.style.display='';
    var fd=new FormData(); fd.append('action','gtbogo_search_categories');
    fd.append('nonce',srchNonce); fd.append('search',q);
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();}).then(function(res){
        if(!res.success||!res.data){box.innerHTML='<div style="padding:12px;color:#64748b;font-size:13px">No results</div>';return;}
        var cats = res.data.categories||res.data||[];
        if(!cats.length){box.innerHTML='<div style="padding:12px;color:#64748b;font-size:13px">No categories found</div>';return;}
        box.innerHTML = cats.map(function(c){
            return '<div onclick="gtbrPickCat('+c.id+',\''+escHtml(c.name)+'\',\''+escHtml(c.count||0)+'\')" '
                +'style="padding:10px 14px;cursor:pointer;font-size:13px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid rgba(255,255,255,0.04)" '
                +'onmouseover="this.style.background=\'rgba(255,255,255,0.05)\'" onmouseout="this.style.background=\'\'">'
                +'<span>'+escHtml(c.name)+'</span>'
                +'<span style="font-size:11px;color:#64748b">'+escHtml(c.count||0)+' products</span>'
                +'</div>';
        }).join('');
    });
}

window.gtbrPickCat = function(id, name, count) {
    selectedCats[id] = name;
    renderChips('cats');
    document.getElementById('gtbr-cat-search').value = '';
    document.getElementById('gtbr-cat-results').style.display = 'none';
};

function gtbrSearchProds(q) {
    var box = document.getElementById('gtbr-prod-results');
    box.innerHTML='<div style="padding:12px;color:#64748b;font-size:13px">Searching...</div>';
    box.style.display='';
    var fd=new FormData(); fd.append('action','gtbogo_search_products');
    fd.append('nonce',srchNonce); fd.append('search',q); fd.append('per_page',20);
    fetch(ajaxUrl,{method:'POST',body:fd,credentials:'same-origin'})
    .then(function(r){return r.json();}).then(function(res){
        if(!res.success||!res.data||!res.data.products){box.innerHTML='<div style="padding:12px;color:#64748b;font-size:13px">No results</div>';return;}
        var prods = res.data.products;
        if(!prods.length){box.innerHTML='<div style="padding:12px;color:#64748b;font-size:13px">No products found</div>';return;}
        box.innerHTML = prods.map(function(p){
            return '<div onclick="gtbrPickProd('+p.id+',\''+escHtml(p.name)+'\')" '
                +'style="padding:10px 14px;cursor:pointer;font-size:13px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid rgba(255,255,255,0.04)" '
                +'onmouseover="this.style.background=\'rgba(255,255,255,0.05)\'" onmouseout="this.style.background=\'\'">'
                +'<div><div style="font-weight:600">'+escHtml(p.name)+'</div>'
                +'<div style="font-size:11px;color:#64748b">'+escHtml(p.type)+(p.sku?' · SKU: '+escHtml(p.sku):'')+'</div></div>'
                +'<span style="font-size:13px;font-weight:700;color:#22c55e">'+escHtml(p.price||'')+'</span>'
                +'</div>';
        }).join('');
    });
}

window.gtbrPickProd = function(id, name) {
    selectedProds[id] = name;
    renderChips('prods');
    document.getElementById('gtbr-prod-search').value = '';
    document.getElementById('gtbr-prod-results').style.display = 'none';
};

})();
