/* Bizmart Admin JS - Financial System */

// Defensive: some setups may reorder/strip localized vars.
// Keep the admin UI functional even if BizmartAnalytics is missing.
window.BizmartAnalytics = window.BizmartAnalytics || {
    ajax_url: window.ajaxurl || '',
    nonce: '',
    currency: (window.BizmartAdmin && BizmartAdmin.currencySymbol) ? BizmartAdmin.currencySymbol : '€',
    admin_lang: 'en'
};

window.BizInvoices = window.BizInvoices || {};
BizInvoices.nonce = (window.BizmartAnalytics && BizmartAnalytics.nonce) ? BizmartAnalytics.nonce : '';

// --- SUPPLIER HANDLERS ---
BizInvoices.createSupplier = async function(data){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_add_supplier');
        form.append('nonce', BizInvoices.nonce);
        form.append('name', data.name);
        form.append('email', data.email||'');
        form.append('phone', data.phone||'');
        form.append('address', data.address||'');
        const res = await fetch(BizmartAnalytics.ajax_url, {method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

// --- PRODUCT HANDLERS ---
BizInvoices.createProduct = async function(data){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_add_product');
        form.append('nonce', BizInvoices.nonce);
        form.append('name', data.name);
        form.append('sku', data.sku||'');
        form.append('default_purchase_price', data.default_purchase_price||0);
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

// --- INVOICE HANDLERS ---
BizInvoices.addInvoice = async function(payload){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_add_invoice');
        form.append('nonce', BizInvoices.nonce);
        form.append('supplier_id', payload.supplier_id);
        form.append('reference_internal', payload.reference_internal || '');
        form.append('reference_supplier', payload.reference_supplier || '');
        form.append('date', payload.date || (function(d){var dt=(d instanceof Date)?d:new Date(d); if(isNaN(dt.getTime())) return ''; var y=dt.getFullYear(), m=String(dt.getMonth()+1).padStart(2,'0'), day=String(dt.getDate()).padStart(2,'0'); return y+'-'+m+'-'+day; })(new Date()));
        form.append('date_supplier', payload.date_supplier || '');
        form.append('items', JSON.stringify(payload.items));
        form.append('notes', payload.notes || '');
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

BizInvoices.editInvoice = async function(payload){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_edit_invoice');
        form.append('nonce', BizInvoices.nonce);
        form.append('invoice_id', payload.invoice_id);
        form.append('supplier_id', payload.supplier_id);
        form.append('reference_internal', payload.reference_internal || '');
        form.append('reference_supplier', payload.reference_supplier || '');
        form.append('date', payload.date);
        form.append('date_supplier', payload.date_supplier || '');
        form.append('status', payload.status);
        form.append('items', JSON.stringify(payload.items));
        form.append('notes', payload.notes || '');
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

BizInvoices.deleteInvoice = async function(invoice_id){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_delete_invoice');
        form.append('nonce', BizInvoices.nonce);
        form.append('invoice_id', invoice_id);
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

// --- PAYMENT HANDLERS ---
BizInvoices.addPayment = async function(invoice_id, amount, method, note, payment_date){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_add_payment');
        form.append('nonce', BizInvoices.nonce);
        form.append('invoice_id', invoice_id);
        form.append('amount', amount);
        form.append('method', method || 'cash');
        form.append('note', note || '');
        form.append('payment_date', payment_date || (function(d){var dt=(d instanceof Date)?d:new Date(d); if(isNaN(dt.getTime())) return ''; var y=dt.getFullYear(), m=String(dt.getMonth()+1).padStart(2,'0'), day=String(dt.getDate()).padStart(2,'0'); return y+'-'+m+'-'+day; })(new Date()));
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

BizInvoices.updatePayment = async function(payment_id, amount, method, note, payment_date){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_update_payment');
        form.append('nonce', BizInvoices.nonce);
        form.append('payment_id', payment_id);
        form.append('amount', amount);
        form.append('method', method || 'cash');
        form.append('note', note || '');
        form.append('payment_date', payment_date || (function(d){var dt=(d instanceof Date)?d:new Date(d); if(isNaN(dt.getTime())) return ''; var y=dt.getFullYear(), m=String(dt.getMonth()+1).padStart(2,'0'), day=String(dt.getDate()).padStart(2,'0'); return y+'-'+m+'-'+day; })(new Date()));
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

BizInvoices.deletePayment = async function(payment_id){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_delete_payment');
        form.append('nonce', BizInvoices.nonce);
        form.append('payment_id', payment_id);
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

// --- SUPPLIER FINANCIAL HANDLERS ---
BizInvoices.getSupplierFinancials = async function(supplier_id){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_get_supplier_financials');
        form.append('nonce', BizInvoices.nonce);
        form.append('supplier_id', supplier_id);
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

BizInvoices.getSupplierTimeline = async function(supplier_id){
    try {
        if (!BizmartAnalytics.ajax_url) return {success:false,message:'Missing AJAX URL'};
        const form = new FormData();
        form.append('action','bizmart_get_supplier_timeline');
        form.append('nonce', BizInvoices.nonce);
        form.append('supplier_id', supplier_id);
        const res = await fetch(BizmartAnalytics.ajax_url,{method:'POST', body:form});
        return res.json();
    } catch(e) {
        console.error(e);
        return {success:false,message:'AJAX error'};
    }
};

// --- PRODUCT SEARCH FOR SELECT2 ---
jQuery(document).ready(function($){
    if (!window.BizmartAnalytics || !BizmartAnalytics.ajax_url) {
        console.warn('BizmartAnalytics.ajax_url missing; Select2 product search disabled');
        return;
    }

    if (typeof $.fn.select2 !== 'function') {
        // Select2 is only enqueued on the invoices screen.
        return;
    }

    $('.biz-product-select').select2({
        placeholder: 'Search for product',
        ajax: {
            url: BizmartAnalytics.ajax_url,
            dataType: 'json',
            delay: 250,
            data: function(params){
                return {
                    action: 'bizmart_search_products',
                    nonce: BizInvoices.nonce,
                    q: params.term
                };
            },
            processResults: function(data){
                return {
                    results: data.success ? data.data.results : []
                };
            },
            cache: true
        },
        templateResult: function(data) {
            if (data.loading) return data.text;
            let html = '<span>' + data.text + '</span>';
            if (data.purchase_price > 0 || data.selling_price > 0) {
                html += '<br><small style="color:#666;">';
                if (data.purchase_price > 0) {
                    html += 'Achat: ' + formatMoney(data.purchase_price) + ' ';
                }
                if (data.selling_price > 0) {
                    html += 'Vente: ' + formatMoney(data.selling_price);
                }
                html += '</small>';
            }
            return $(html);
        },
        minimumInputLength: 1
    });
    
    function formatMoney(amount) {
        return parseFloat(amount).toFixed(2) + ' ' + (BizmartAnalytics.currency || ((window.BizmartAdmin && BizmartAdmin.currencySymbol) ? BizmartAdmin.currencySymbol : '€'));
    }
});

// Ensure export forms open in a new tab to reliably download CSV
document.addEventListener('DOMContentLoaded', function(){
    try {
        var forms = document.querySelectorAll('form');
        forms.forEach(function(f){
            var actionInput = f.querySelector('input[name="action"][value="bizmart_export_products"]');
            if (actionInput) {
                f.setAttribute('target', '_blank');
            }
        });
    } catch(e) { console.error(e); }
});
