<?php defined('ABSPATH') || exit;
$_gate=\DZQCOD\Modules::addon_gate(['yalidine','zr-express','ecotrack','noest'],'🚚 الشحن'); if($_gate){echo esc_html($_gate);return;}
$S=\DZQCOD\Core::ST;
$provider = \DZQCOD\Core::opt('shipping_provider','yalidine');
$providers = class_exists('\DZQCOD\Shipping') ? \DZQCOD\Shipping::get_providers() : ['yalidine'=>['name'=>'Yalidine','icon'=>'🚚'],'zr'=>['name'=>'ZR Express','icon'=>'📦'],'ecotrack'=>['name'=>'EcoTrack','icon'=>'🌿']];
$ready=wc_get_orders(['status'=>['wc-confirmed','wc-ready-to-ship'],'limit'=>100,'orderby'=>'date']);
$shipped=wc_get_orders(['status'=>['wc-shipped','wc-in-transit','wc-out-for-delivery'],'limit'=>50,'orderby'=>'date','order'=>'DESC']);
$delivered_today = count(wc_get_orders(['status'=>'wc-delivered','date_created'=>'>'.gmdate('Y-m-d'),'limit'=>-1,'return'=>'ids']));
$rto_today = count(wc_get_orders(['status'=>'wc-rto','date_created'=>'>'.gmdate('Y-m-d'),'limit'=>-1,'return'=>'ids'])); ?>
<div class="wrap dza-wrap" dir="rtl">
<div class="dza-header"><h1>الشحن</h1>
<div style="display:flex;gap:8px;align-items:center">
<select id="ship-provider" style="padding:8px 14px;border:1px solid #ddd;border-radius:8px;font-size:13px">
<?php foreach($providers as $k=>$p): ?><option value="<?php echo esc_html($k); ?>" <?php selected($provider,$k); ?>><?php echo esc_html($p['icon'].' '.$p['name']); ?></option><?php endforeach; ?>
</select>
<button class="dza-btn primary" id="bulk-ship-btn" disabled>🚚 شحن (<span id="sel-count">0</span>)</button>
<button class="dza-btn" id="test-conn-btn">🔌 اختبار</button>
<button class="dza-btn" onclick="showRates()" style="background:#10B981;color:#fff">💰 التسعير</button>
</div>
<!-- Provider Features -->
<div id="provider-features" style="margin-top:12px;display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:6px;font-size:11px">
</div>
<script>
var provFeatures={
    yalidine:{label:'Yalidine',features:['✅ تسعير تلقائي','✅ إنشاء شحنة','✅ تتبع حي','✅ Webhook','✅ بوليصة','✅ Stop Desk','✅ 58 ولاية'],color:'#e74c3c'},
    zr:{label:'ZR Express',features:['✅ تسعير تلقائي','✅ إنشاء شحنة','✅ تتبع','✅ Webhook','✅ Stop Desk','✅ 58 ولاية'],color:'#3498db'},
    ecotrack:{label:'EcoTrack',features:['✅ تسعير تلقائي','✅ إنشاء شحنة','✅ تتبع','✅ Webhook','✅ DHD/Connexlog','✅ 58 ولاية'],color:'#27ae60'},
    noest:{label:'NOEST',features:['✅ تسعير حسب الولاية','✅ إنشاء + تأكيد','✅ تتبع حي','✅ Webhook','✅ Stop Desk','✅ بوليصة','✅ مزامنة أسعار'],color:'#2980b9'},
    maystro:{label:'Maystro Delivery',features:['✅ تسعير تلقائي','✅ إنشاء شحنة','✅ تتبع','✅ Webhook','✅ منزل/مكتب','✅ 58 ولاية'],color:'#e67e22'},
    procolis:{label:'ProColis',features:['✅ تسعير تلقائي','✅ إنشاء شحنة','✅ تتبع','✅ Webhook','✅ Stop Desk','✅ API ZR'],color:'#8e44ad'},
    guepex:{label:'Guepex',features:['✅ تسعير تلقائي','✅ إنشاء شحنة','✅ تتبع','✅ Webhook','✅ نقاط استلام','✅ 58 ولاية'],color:'#f39c12'}
};
function updateFeatures(){var p=jQuery('#ship-provider').val(),f=provFeatures[p];if(!f)return;
var h='';f.features.forEach(function(ft){h+='<span style="background:'+f.color+'15;color:'+f.color+';padding:4px 8px;border-radius:6px;font-weight:700">'+ft+'</span>'});
jQuery('#provider-features').html(h)}
jQuery('#ship-provider').on('change',updateFeatures);jQuery(updateFeatures);
function showRates(){jQuery.post(dza.ajax,{action:'dzqcod_ship_rates',nonce:dza.nonce,provider:jQuery('#ship-provider').val()},function(r){
    if(!r.success||!r.data.length){alert('لا توجد أسعار');return}var h='<div style="max-height:400px;overflow-y:auto"><table class="dza-table"><thead><tr><th>الولاية</th><th>منزل</th><th>مكتب</th><th>مرتجع</th></tr></thead><tbody>';
    r.data.forEach(function(f){h+='<tr><td>'+(f.wilaya_name||'ولاية '+f.wilaya_id)+'</td><td style="font-weight:700;color:#10B981">'+(f.tarif_home||'-')+' دج</td><td>'+(f.tarif_desk||'-')+' دج</td><td style="color:#e74c3c">'+(f.return_home||f.return_fee||'-')+' دج</td></tr>'});
    h+='</tbody></table></div>';var w=window.open('','_blank','width=600,height=500');w.document.write('<html dir=rtl><head><title>💰 التسعير</title><style>*{font-family:Tajawal,sans-serif}table{width:100%;border-collapse:collapse}th{background:#6366F1;color:#fff;padding:8px}td{padding:6px 8px;border-bottom:1px solid #eee;font-size:13px}tr:hover{background:#f0f0f0}</style></head><body style=padding:20px><h2>💰 تسعير '+jQuery('#ship-provider option:selected').text()+'</h2>'+h+'</body></html>')})}
</script>
<?php include __DIR__.'/nav.php'; ?>
<div class="dza-content">
<div class="dza-kpi-grid" style="grid-template-columns:repeat(4,1fr);margin-bottom:20px">
<div class="dza-card" style="text-align:center;border-top:3px solid #f39c12"><div style="font-size:28px;font-weight:800;color:#f39c12"><?php echo (int)count($ready); ?></div><div style="font-size:12px;color:#888">جاهزة</div></div>
<div class="dza-card" style="text-align:center;border-top:3px solid #3498db"><div style="font-size:28px;font-weight:800;color:#3498db"><?php echo (int)count($shipped); ?></div><div style="font-size:12px;color:#888">مشحونة</div></div>
<div class="dza-card" style="text-align:center;border-top:3px solid #27ae60"><div style="font-size:28px;font-weight:800;color:#27ae60"><?php echo esc_html($delivered_today); ?></div><div style="font-size:12px;color:#888">موصّل اليوم</div></div>
<div class="dza-card" style="text-align:center;border-top:3px solid #e74c3c"><div style="font-size:28px;font-weight:800;color:#e74c3c"><?php echo esc_html($rto_today); ?></div><div style="font-size:12px;color:#888">مرتجع</div></div>
</div>
<h2 class="dza-section-title">📦 جاهزة للشحن (<?php echo (int)count($ready); ?>)</h2>
<table class="dza-table"><thead><tr><th><input type="checkbox" id="check-all-ship"></th><th>#</th><th>العميل</th><th>الهاتف</th><th>الولاية</th><th>البلدية</th><th>المبلغ</th><th>إجراء</th></tr></thead><tbody>
<?php if(empty($ready)): ?><tr><td colspan="8" class="empty">🎉 لا توجد طلبات</td></tr>
<?php else: foreach($ready as $o): ?>
<tr><td><input type="checkbox" class="order-check" value="<?php echo (int)$o->get_id(); ?>"></td>
<td>#<?php echo (int)$o->get_id(); ?></td><td><?php echo esc_html($o->get_billing_first_name()); ?></td>
<td class="ltr"><?php echo esc_html($o->get_billing_phone()); ?></td><td><?php echo esc_html($o->get_shipping_state()); ?></td>
<td><?php echo esc_html($o->get_shipping_city()); ?></td>
<td class="bold"><?php echo number_format((float)$o->get_total(),0); ?> دج</td>
<td><a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-orders&id='.$o->get_id())); ?>" class="dza-btn sm" title="عرض الطلب">👁</a> <button class="dza-btn sm primary ship-single" data-id="<?php echo (int)$o->get_id(); ?>">🚚</button> <button class="dza-btn sm print-receipt" data-id="<?php echo (int)$o->get_id(); ?>">🖨️</button></td></tr>
<?php endforeach; endif; ?></tbody></table>
<h2 class="dza-section-title" style="margin-top:24px">🚛 مشحونة (<?php echo (int)count($shipped); ?>)</h2>
<table class="dza-table"><thead><tr><th>#</th><th>العميل</th><th>الولاية</th><th>الشركة</th><th>التتبع</th><th>الحالة</th><th>التاريخ</th><th></th></tr></thead><tbody>
<?php if(empty($shipped)): ?><tr><td colspan="8" class="empty">لا توجد شحنات</td></tr>
<?php else: foreach($shipped as $o): $st=str_replace('wc-','',$o->get_status()); $sc=$S[$st]??['l'=>$st,'c'=>'#999']; $trk=$o->get_meta('_dzqcod_tracking_number'); $sprov=$o->get_meta('_dzqcod_shipping_provider'); ?>
<tr><td>#<?php echo (int)$o->get_id(); ?></td><td><?php echo esc_html($o->get_billing_first_name()); ?></td><td><?php echo esc_html($o->get_shipping_state()); ?></td>
<td style="font-size:11px"><?php echo esc_html($providers[$sprov]['name']??$sprov??'-'); ?></td>
<td style="font-family:monospace;font-size:11px;direction:ltr"><?php echo esc_html($trk?:'-'); ?></td>
<td><span class="dza-badge" style="background:<?php echo esc_html($sc['c']); ?>"><?php echo esc_html($sc['l']); ?></span></td>
<td class="sm"><?php echo esc_html($o->get_date_modified()?$o->get_date_modified()->format('m/d H:i'):'-'); ?></td>
<td><a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-orders&id='.$o->get_id())); ?>" class="dza-btn sm" title="عرض">👁</a> <button class="dza-btn sm print-receipt" data-id="<?php echo (int)$o->get_id(); ?>" title="طباعة">🖨️</button> <?php if($trk): ?><button class="dza-btn sm track-btn" data-id="<?php echo (int)$o->get_id(); ?>">🔍</button> <button class="dza-btn sm label-btn" data-id="<?php echo (int)$o->get_id(); ?>">🏷️</button><?php endif; ?></td></tr>
<?php endforeach; endif; ?></tbody></table>
<div class="dza-card" style="margin-top:20px;display:flex;align-items:center;justify-content:space-between;background:#f0f9ff;border:1px solid #93c5fd">
<div><strong>⚙️ إعدادات الشحن</strong><p style="font-size:12px;color:#64748b;margin:4px 0 0">API Keys والإعدادات انتقلت إلى صفحة الإعدادات > تبويب الشحن</p></div>
<a href="<?php echo esc_url(admin_url('admin.php?page=dzqcod-settings&stab=shipping')); ?>" class="dza-btn primary" style="font-size:13px">⚙️ إعدادات الشحن</a>
</div></div>
</div></div>
<div id="track-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;justify-content:center;align-items:center" onclick="if(event.target===this)this.style.display='none'">
<div style="background:#fff;border-radius:14px;max-width:480px;width:90%;padding:20px;direction:rtl"><div style="display:flex;justify-content:space-between;margin-bottom:10px"><h3 id="track-title">🔍</h3><button onclick="document.getElementById('track-modal').style.display='none'" style="background:none;border:none;font-size:20px;cursor:pointer">✕</button></div><div id="track-content"></div></div></div>
<div id="label-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99999;justify-content:center;align-items:center" onclick="if(event.target===this)this.style.display='none'">
<div style="background:#fff;border-radius:14px;max-width:480px;width:90%;padding:20px;direction:rtl"><div style="display:flex;justify-content:space-between;margin-bottom:10px"><div><button onclick="window.print()" class="dza-btn sm primary">🖨️</button></div><button onclick="document.getElementById('label-modal').style.display='none'" style="background:none;border:none;font-size:20px;cursor:pointer">✕</button></div><div id="label-content"></div></div></div>
<script>jQuery(function($){
var upd=function(){var c=$('.order-check:checked').length;$('#sel-count').text(c);$('#bulk-ship-btn').prop('disabled',c<1)};
$('#check-all-ship').on('change',function(){$('.order-check').prop('checked',$(this).is(':checked'));upd()});
$(document).on('change','.order-check',upd);
$(document).on('click','.ship-single',function(){var $b=$(this),id=$b.data('id');if(!confirm('شحن #'+id+'?'))return;$b.prop('disabled',1).text('⏳');
$.post(dza.ajax,{action:'dzqcod_ship_create',nonce:dza.nonce,order_id:id,provider:$('#ship-provider').val()},function(r){if(r.success){$b.closest('tr').fadeOut();alert('✅ '+(r.data.tracking||''))}else alert('❌ '+(r.data?r.data.message:''));$b.prop('disabled',0).text('🚚')})});
$('#bulk-ship-btn').on('click',function(){var ids=$('.order-check:checked').map(function(){return $(this).val()}).get();if(!ids.length||!confirm('شحن '+ids.length+'?'))return;var $b=$(this);$b.prop('disabled',1).text('⏳');
$.post(dza.ajax,{action:'dzqcod_ship_bulk',nonce:dza.nonce,order_ids:ids,provider:$('#ship-provider').val()},function(r){alert(r.success?'✅ '+r.data.success+' نجح | '+r.data.failed+' فشل':'❌');location.reload()})});
$(document).on('click','.track-btn',function(){var id=$(this).data('id');$('#track-title').text('🔍 #'+id);$('#track-content').html('⏳');$('#track-modal').css('display','flex');
$.post(dza.ajax,{action:'dzqcod_ship_track',nonce:dza.nonce,order_id:id},function(r){if(r.success){var d=r.data,h='<div style="text-align:center;background:#f5f5f5;padding:10px;border-radius:8px;margin-bottom:8px"><strong style="font-family:monospace;font-size:16px">'+d.tracking+'</strong><br><span style="color:#666">'+d.provider+'</span></div><div style="font-weight:700;margin-bottom:6px">الحالة: '+d.status+'</div>';if(d.history)d.history.forEach(function(e){h+='<div style="font-size:11px;padding:3px 0;border-bottom:1px solid #f0f0f0"><b>'+e.date+'</b> '+e.status+'</div>'});$('#track-content').html(h)}else $('#track-content').html('❌')})});
$(document).on('click','.label-btn',function(){var id=$(this).data('id');$('#label-content').html('⏳');$('#label-modal').css('display','flex');
$.post(dza.ajax,{action:'dzqcod_ship_label',nonce:dza.nonce,order_id:id},function(r){$('#label-content').html(r.success?r.data.html:'❌')})});

</div><!--dza-main-->
</div><!--dza-layout-->
