/* DZQCOD v3 Admin — Dashboard */
(function($){
'use strict';

// ═══ GLOBAL UX HELPERS ═══
window.dzToast=function(msg,type){
    type=type||'info';
    var t=$('<div class="dza-toast '+type+'">'+msg+'</div>').appendTo('body');
    setTimeout(function(){t.fadeOut(300,function(){t.remove()})},3000);
};
window.dzConfirm=function(msg,cb){if(confirm(msg))cb()};

$(function(){
    // ═══ SIDEBAR ═══
    var $side = $('#dza-side');
    // Close sidebar when clicking a link (mobile)
    $side.on('click', '.dza-side-link', function(){ if($(window).width() <= 960) $side.removeClass('open'); });
    // Close on click outside (mobile)
    $(document).on('click', function(e){
        if($(window).width()<=960 && $side.hasClass('open') && !$(e.target).closest('#dza-side,#dza-menu-btn').length) $side.removeClass('open');
    });
    // ESC closes
    $(document).on('keydown', function(e){ if(e.key==='Escape') $side.removeClass('open'); });
    // ═══ PRINTING ═══
    $(document).on('click','.print-receipt',function(){
        var id=$(this).data('id'),$b=$(this);$b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_print_receipt',nonce:dza.nonce,order_id:id},function(r){
            if(r.success&&r.data.html){var w=window.open('','_blank','width=420,height=600');
            w.document.write('<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="UTF-8"><link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+39&display=swap" rel="stylesheet"><title>طباعة #'+id+'</title><style>body{margin:10px;font-family:Arial,Tahoma,sans-serif}@media print{body{margin:0}}</style></head><body>');
            w.document.write(r.data.html);w.document.write('<script>setTimeout(function(){window.print()},300)<\/script></body></html>');w.document.close();}
            else alert('خطأ في تحميل الوصل');
        }).always(function(){$b.prop('disabled',false).text('🖨️')});
    });

    // ═══ BATCH PRINT ═══
    $('#batch-print').on('click',function(){
        var ids=[];$('.order-check:checked').each(function(){ids.push($(this).val())});
        if(!ids.length){alert('اختر طلبات');return}
        $.post(dza.ajax,{action:'dzqcod_print_batch',nonce:dza.nonce,order_ids:ids},function(r){
            if(r.success&&r.data.html){var w=window.open('','_blank');w.document.write(r.data.html);
            w.document.write('<script>setTimeout(function(){window.print()},300)<\/script>');w.document.close();}});
    });

    // ═══ CHECK ALL ═══
    $(document).on('change','#check-all,#thead-check,.check-all-ship',function(){$(this).closest('table,.dza-batch-bar').parent().find('.order-check').prop('checked',$(this).is(':checked'))});

    // ═══ BATCH ACTIONS ═══
    $('#batch-run').on('click',function(){
        var action=$('#batch-action').val(),ids=[];$('.order-check:checked').each(function(){ids.push($(this).val())});
        if(!action||!ids.length){alert('اختر إجراء وطلبات');return}
        if(action==='print'){$('#batch-print').trigger('click');return}
        if(action==='ship'){if(!confirm('شحن '+ids.length+' طلب؟'))return;
        ids.forEach(function(id){$.post(dza.ajax,{action:'dzqcod_create_shipment',nonce:dza.nonce,order_id:id})});
        setTimeout(function(){location.reload()},1500);return}
        if(!confirm('تنفيذ "'+action+'" على '+ids.length+' طلب؟'))return;
        ids.forEach(function(id){$.post(dza.ajax,{action:'dzqcod_update_order_status',nonce:dza.nonce,order_id:id,status:'wc-'+action})});
        setTimeout(function(){location.reload()},1500);
    });

    // ═══ DELETE ORDER ═══
    $(document).on('click','.order-delete',function(){
        var $b=$(this),id=$b.data('id');
        if(!confirm('حذف الطلب #'+id+'؟ سيتم نقله للمحذوفات'))return;
        $b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_delete_order',nonce:dza.nonce,order_id:id},function(r){
            if(r.success){$b.closest('tr').fadeOut(300,function(){$(this).remove()});}
            else{alert(r.data&&r.data.message?r.data.message:'خطأ');$b.prop('disabled',false).text('🗑️');}
        });
    });

    // ═══ DELETE PRODUCT ═══
    $(document).on('click','.dzp-delete',function(){
        var $b=$(this),id=$b.data('id'),name=$b.closest('tr').find('td:eq(1)').text().trim();
        if(!confirm('حذف المنتج "'+name+'"؟\nسيتم نقله للمحذوفات'))return;
        $b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_delete_product',nonce:dza.nonce,product_id:id},function(r){
            if(r.success){$b.closest('tr').fadeOut(300,function(){$(this).remove()});}
            else{alert(r.data&&r.data.message?r.data.message:'خطأ');$b.prop('disabled',false).text('🗑️');}
        });
    });

    // ═══ DELETE WILAYA ═══
    $(document).on('click','.wil-delete',function(){
        var $b=$(this),code=$b.data('code'),name=$b.data('name');
        if(!confirm('⚠️ حذف ولاية "'+name+'" ('+code+')؟\nسيتم حذف جميع البلديات التابعة لها نهائياً!'))return;
        $b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_delete_wilaya',nonce:dza.nonce,wilaya_code:code},function(r){
            if(r.success){$b.closest('tr').fadeOut(300,function(){$(this).remove()});}
            else{alert(r.data&&r.data.message?r.data.message:'خطأ');$b.prop('disabled',false).text('🗑️');}
        });
    });

    // ═══ BATCH DELETE ORDERS ═══
    // Handle 'delete' in batch actions
    $(document).on('change','#batch-action',function(){
        if($(this).val()==='delete'){
            var ids=[];$('.order-check:checked').each(function(){ids.push($(this).val())});
            if(!ids.length){alert('اختر طلبات');$(this).val('');return}
            if(!confirm('حذف '+ids.length+' طلب؟')){$(this).val('');return}
            ids.forEach(function(id){$.post(dza.ajax,{action:'dzqcod_delete_order',nonce:dza.nonce,order_id:id})});
            setTimeout(function(){location.reload()},1500);
        }
    });

    // ═══ CALL CENTER ═══
    $(document).on('click','.log-call',function(){
        var $b=$(this),id=$b.data('id'),outcome=$b.data('outcome'),notes=$('.call-notes[data-id='+id+']').val()||'';
        $b.prop('disabled',true).css('opacity','.5');
        $.post(dza.ajax,{action:'dzqcod_log_call',nonce:dza.nonce,order_id:id,outcome:outcome,notes:notes},function(r){
            if(r.success)$b.closest('.dza-call-card').fadeOut(400,function(){$(this).remove()});
            else{$b.prop('disabled',false).css('opacity','1');alert('خطأ')}});
    });

    // ═══ SHIPPING ═══
    $(document).on('click','.ship-single',function(){
        var $b=$(this),id=$b.data('id');if(!confirm('شحن #'+id+'؟'))return;
        $b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_create_shipment',nonce:dza.nonce,order_id:id},function(r){
            if(r.success)$b.closest('tr').fadeOut();else{$b.prop('disabled',false).text('🚚 شحن');alert('خطأ')}});
    });

    // ═══ LICENSE ═══
    $('#activate-lic').on('click',function(){
        var key=$('#lic-key').val();if(!key){alert('أدخل المفتاح');return}
        var $btn=$(this);$btn.prop('disabled',true).text('⏳ جاري التحقق...');
        $.ajax({
            url:dza.ajax, type:'POST', timeout:20000,
            data:{action:'dzqcod_activate_license',nonce:dza.nonce,license_key:key},
            success:function(r){
                if(r.success){
                    alert(r.data.message||'✅ تم التفعيل');
                    location.reload();
                } else {
                    alert('❌ '+(r.data&&r.data.message?r.data.message:'فشل التفعيل'));
                    $btn.prop('disabled',false).text('🔓 تفعيل');
                }
            },
            error:function(xhr,status,err){
                if(status==='timeout'){
                    alert('⏱️ انتهت مهلة الاتصال بسيرفر الترخيص. حاول مرة أخرى.');
                } else {
                    alert('❌ خطأ في الاتصال: '+(err||status));
                }
                $btn.prop('disabled',false).text('🔓 تفعيل');
            }
        });
    });
    $('#deactivate-lic').on('click',function(){
        if(!confirm('إلغاء تفعيل الترخيص؟'))return;
        var $btn=$(this);$btn.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_deactivate_license',nonce:dza.nonce},function(){location.reload()}).fail(function(){alert('خطأ');$btn.prop('disabled',false).text('🔒 إلغاء')});
    });

    // ═══ OFFERS ═══
    $('#save-offer').on('click',function(){
        $.post(dza.ajax,{action:'dzqcod_save_offer',nonce:dza.nonce,name:$('#of-name').val(),type:$('#of-type').val(),value:$('#of-value').val()},function(r){
            if(r.success)location.reload();else alert('خطأ')});
    });
    $(document).on('click','.del-offer',function(){
        if(!confirm('حذف العرض؟'))return;var id=$(this).data('id');
        $.post(dza.ajax,{action:'dzqcod_delete_offer',nonce:dza.nonce,offer_id:id},function(){location.reload()});
    });

    // ═══ FRAUD BLACKLIST ═══
    $('#add-blacklist').on('click',function(){
        var type=$('#bl-type').val(),val=$('#bl-value').val(),reason=$('#bl-reason').val();
        if(!val){alert('أدخل القيمة');return}
        $.post(dza.ajax,{action:'dzqcod_fraud_blacklist',nonce:dza.nonce,type:type,value:val,reason:reason},function(r){
            if(r.success){alert(r.data.message);location.reload()}});
    });

    // ═══ SETTINGS SAVE ═══
    $('#save-all-settings').on('click',function(){
        var s={};$('.gen-setting').each(function(){
            var k=$(this).data('key');if(!k)return;
            if($(this).is(':checkbox'))s[k]=$(this).is(':checked')?'yes':'no';
            else s[k]=$(this).val();
        });
        $(this).prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_save_settings',nonce:dza.nonce,settings:s},function(r){
            $('#save-all-settings').prop('disabled',false).text('💾 حفظ الكل');
            if(r.success){dzToast('✅ تم حفظ جميع الإعدادات','success')}else{dzToast('❌ فشل الحفظ','error')}
        }).fail(function(){$('#save-all-settings').prop('disabled',false).text('💾 حفظ الكل');dzToast('❌ خطأ اتصال','error')});
    });

    // ═══ REMOTE ADDONS REFRESH ═══
    $('#refresh-addons').on('click',function(){
        $(this).prop('disabled',true).text('⏳ جاري التحديث...');
        $.post(dza.ajax,{action:'dzqcod_refresh_remote_addons',nonce:dza.nonce},function(r){
            $('#refresh-addons').prop('disabled',false).text('🔄 تحديث');
            if(r.success){alert(r.data.message);location.reload()}else alert('فشل التحديث')});
    });

    // ═══ ADDONS INSTALL/TOGGLE ═══
    $(document).on('click','.install-addon',function(){
        var slug=$(this).data('slug'),$b=$(this);$b.prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_install_addon',nonce:dza.nonce,slug:slug},function(r){
            if(r.success){$b.text('✅').removeClass('primary').addClass('success');setTimeout(function(){location.reload()},800)}
            else{$b.prop('disabled',false).text('❌ '+(r.data?r.data.message:'خطأ'))}});
    });
    $(document).on('click','.toggle-addon',function(){
        var slug=$(this).data('slug'),$b=$(this);$b.prop('disabled',true);
        $.post(dza.ajax,{action:'dzqcod_toggle_addon',nonce:dza.nonce,slug:slug},function(r){
            if(r.success)location.reload();else $b.prop('disabled',false)});
    });

    // ═══ PROFIT CALCULATOR ═══
    $('#calc-profit').on('click',function(){
        $(this).prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_profit_calc',nonce:dza.nonce,from:$('#prof-from').val(),to:$('#prof-to').val()},function(r){
            $('#calc-profit').prop('disabled',false).text('📊 حساب');
            if(!r.success)return;var d=r.data;
            $('#pr-revenue').text(d.revenue.toLocaleString()+' دج');
            $('#pr-cost').text(d.product_cost.toLocaleString()+' دج');
            $('#pr-shipping').text(d.shipping_cost.toLocaleString()+' دج');
            $('#pr-ads').text(d.ad_spend.toLocaleString()+' دج');
            $('#pr-rto').text(d.rto_loss.toLocaleString()+' دج');
            $('#pr-net').text(d.net_profit.toLocaleString()+' دج').css('color',d.net_profit>=0?'#27ae60':'#e74c3c');
            $('#pr-margin').text(d.margin+'%');$('#pr-roas').text(d.roas+'x');
            $('#pr-orders').text(d.orders_delivered+' موصّل / '+d.orders_rto+' مرتجع');
            $('#pr-avg').text(d.avg_order.toLocaleString()+' دج')});
    });

    // ═══ COHORT ANALYSIS ═══
    $('#load-cohort').on('click',function(){
        $(this).prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_cohort_data',nonce:dza.nonce},function(r){
            $('#load-cohort').prop('disabled',false).text('📊 تحميل');
            if(!r.success)return;var h='<table class="dza-table"><thead><tr><th>الشهر</th><th>عملاء جدد</th><th>طلبات</th><th>شهر 1</th><th>شهر 2</th><th>شهر 3</th></tr></thead><tbody>';
            r.data.cohorts.forEach(function(c){h+='<tr><td>'+c.month+'</td><td>'+c.new_customers+'</td><td>'+c.orders+'</td>';
                h+='<td>'+(c.retention.month_1||'-')+'%</td><td>'+(c.retention.month_2||'-')+'%</td><td>'+(c.retention.month_3||'-')+'%</td></tr>'});
            h+='</tbody></table>';$('#cohort-results').html(h)});
    });

    // ═══ HEATMAP DATA ═══
    $('#load-heatmap').on('click',function(){
        $(this).prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_heatmap_data',nonce:dza.nonce},function(r){
            $('#load-heatmap').prop('disabled',false).text('🔥 تحميل');
            if(!r.success)return;var h='<table class="dza-table"><thead><tr><th>الحقل</th><th>النوع</th><th>المرات</th><th>متوسط الوقت</th></tr></thead><tbody>';
            r.data.fields.forEach(function(f){h+='<tr><td>'+f.field+'</td><td>'+f.event_type+'</td><td>'+f.count+'</td><td>'+Math.round(f.avg_time)+'ث</td></tr>'});
            h+='</tbody></table>';if(r.data.drop_off.length){h+='<h4 style="margin-top:12px">⚠️ أعلى نقاط ترك</h4><ul>';
            r.data.drop_off.forEach(function(d){h+='<li>'+d.field+': '+d.count+' ترك</li>'});h+='</ul>'}
            $('#heatmap-results').html(h)});
    });

    // ═══ INTEGRATIONS SAVE ═══
    $('#save-integrations').on('click',function(){
        var s={};$('.int-setting').each(function(){s[$(this).data('key')]=$(this).is(':checkbox')?$(this).is(':checked')?'yes':'no':$(this).val()});
        $(this).prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_save_integrations',nonce:dza.nonce,settings:s},function(r){
            $('#save-integrations').prop('disabled',false).text(r.success?'✅ تم!':'❌');
            setTimeout(function(){$('#save-integrations').text('💾 حفظ')},2000)});
    });

    // ═══ SALESBOOST CONFIG SAVES ═══
    $('#save-upsell-cfg').on('click',function(){
        $.post(dza.ajax,{action:'dzqcod_save_upsell_config',nonce:dza.nonce,
            upsell_enabled:$('#upsell-on').is(':checked')?'yes':'no',
            bump_discount:$('#bump-disc').val(),bump_title:$('#bump-title').val()},function(){location.reload()})});
    $('#save-loyalty-cfg').on('click',function(){
        $.post(dza.ajax,{action:'dzqcod_save_loyalty_config',nonce:dza.nonce,
            loyalty_enabled:$('#loyalty-on').is(':checked')?'yes':'no',
            loyalty_points_per_1000:$('#lp-per-k').val(),loyalty_redeem_rate:$('#lp-redeem').val()},function(){location.reload()})});
    $('#save-referral-cfg').on('click',function(){
        $.post(dza.ajax,{action:'dzqcod_save_referral_config',nonce:dza.nonce,
            referral_enabled:$('#ref-on').is(':checked')?'yes':'no',
            referral_commission:$('#ref-pct').val(),referral_loyalty_bonus:$('#ref-bonus').val()},function(){location.reload()})});

    // ═══ SMARTOPS CONFIG ═══
    $('#save-smart-cfg').on('click',function(){
        var s={};$('.smart-setting').each(function(){s[$(this).data('key')]=$(this).is(':checkbox')?$(this).is(':checked')?'yes':'no':$(this).val()});
        $.post(dza.ajax,{action:'dzqcod_save_settings',nonce:dza.nonce,settings:s},function(r){
            if(r.success)alert('✅ تم الحفظ');else alert('❌ خطأ')});
    });

    // ═══ WHATSAPP SEND MESSAGE ═══
    $(document).on('click','.send-wa',function(){
        var oid=$(this).data('id'),tpl=$(this).data('tpl')||'order_confirm';
        $(this).prop('disabled',true).text('⏳');
        $.post(dza.ajax,{action:'dzqcod_send_message',nonce:dza.nonce,order_id:oid,template:tpl,channel:'whatsapp'},function(r){
            alert(r.success?'✅ تم الإرسال':'❌ '+(r.data?r.data.message:'خطأ'))}).always(function(){$('.send-wa[data-id='+oid+']').prop('disabled',false).text('📱')});
    });
});
})(jQuery);
